﻿using System;
using System.IO;
using System.Web;
using System.Web.Mvc;
using Inscriptionem.Areas.Inscriptionem.Models.Enums;
using Inscriptionem.Areas.Inscriptionem.Models.Views;
using Inscriptionem.Authorization;
using Inscriptionem.Controllers;

namespace Inscriptionem.Areas.Inscriptionem.Controllers
{
    [InscriptionemAuthorize(MemberRole.Admin, MemberRole.Moderator, MemberRole.Writer)]
    public class UploadController : Controller
    {
        private static readonly string DirectoryPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Uploaded");

        public ActionResult Index()
        {
            return View("Index", new UploadCollectionViewModel(DirectoryPath));
        }

        public ActionResult Page(int ID)
        {
            if (ID <= 0)
            {
                return RedirectToAction("Index");
            }

            return View("Index", new UploadCollectionViewModel(DirectoryPath) { Page = ID });
        }

        public ActionResult Add()
        {
            return View("Add", new UploadViewModel());
        }

        [HttpPost]
        public ActionResult Add(HttpPostedFileBase file)
        {
            if (file.ContentLength == 0)
            {
                return View("Add", new UploadViewModel() {Error = UploadError.FileEmpty});
            }

            var fileName = Path.GetFileName(file.FileName);
            var path = Path.Combine(DirectoryPath, fileName);
            file.SaveAs(path);

            return View("Add", new UploadViewModel());
        }

        [HttpPost]
        public ActionResult Delete(string FileName)
        {
            if (!string.IsNullOrWhiteSpace(FileName) && Directory.Exists(DirectoryPath))
            {
                string fileName = Path.Combine(DirectoryPath, FileName);
                if (System.IO.File.Exists(fileName))
                {
                    System.IO.File.Delete(fileName);
                }
            }

            return RedirectToAction("Index");
        }

        #region Pagination
        public ActionResult Pagination(global::Inscriptionem.Models.Menu.Requests.PaginationRequestModel model)
        {
            return new MenuController().Pagination(model);
        }
        #endregion
    }
}
